<template>
  <view class="location-search">
    <!-- 搜索框 -->
    <view class="search-box">
      <view class="search-input-wrap">
        <input 
          class="search-input" 
          v-model="searchKeyword" 
          placeholder="搜索地点" 
          confirm-type="search"
          @confirm="handleSearch"
        />
        <view v-if="searchKeyword" class="clear-icon" @click="searchKeyword = ''">×</view>
      </view>
      <view class="search-btn" @click="handleSearch">搜索</view>
      <view class="cancel-btn" @click="goBack">取消</view>
    </view>
    
    <!-- 搜索结果 -->
    <view class="search-results" v-if="searchResults.length > 0">
      <view 
        class="location-item" 
        v-for="(item, index) in searchResults" 
        :key="index"
        @click="selectLocation(item)"
      >
        <view class="item-left">
          <view class="item-icon">📍</view>
          <view class="location-info">
            <text class="location-name">{{ item.name }}</text>
            <text class="location-address">{{ item.address }}</text>
          </view>
        </view>
        <view class="item-right">›</view>
      </view>
    </view>
    
    <!-- 搜索为空 -->
    <view class="empty-result" v-else-if="hasSearched">
      <view class="empty-content">
        <view class="empty-icon">🔍</view>
        <text class="empty-text">未找到相关位置</text>
      </view>
    </view>
    
    <!-- 默认显示热门城市 -->
    <view class="hot-cities" v-else>
      <view class="section-title">热门城市</view>
      <view class="city-grid">
        <view 
          class="city-item" 
          v-for="(city, index) in hotCities" 
          :key="index"
          @click="selectCity(city)"
        >
          <text>{{ city }}</text>
        </view>
      </view>
      
      <view class="section-title">历史搜索</view>
      <view class="history-list" v-if="searchHistory.length > 0">
        <view 
          class="history-item" 
          v-for="(item, index) in searchHistory" 
          :key="index"
          @click="selectLocation({name: item, address: ''})"
        >
          <view class="item-left">
            <view class="history-icon">⏱️</view>
            <text class="history-text">{{ item }}</text>
          </view>
          <view class="close-btn" @click.stop="removeHistory(index)">×</view>
        </view>
      </view>
      <view class="empty-history" v-else>
        <text>暂无搜索历史</text>
      </view>
    </view>
    
    <!-- 加载更多 -->
    <view class="loading-more" v-if="searchResults.length > 0 && isLoading">
      <text>加载中...</text>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { getSuggestion, getCityList } from '@/api/location';

const searchKeyword = ref('');
const searchResults = ref([]);
const hasSearched = ref(false);
const isLoading = ref(false);
const searchHistory = ref([]);
const hotCities = ref([]);
const currentRegion = ref('全国');

// 初始化
onMounted(async () => {
  // 从本地存储获取搜索历史
  const history = uni.getStorageSync('locationSearchHistory');
  if (history) {
    try {
      searchHistory.value = JSON.parse(history);
    } catch (e) {
      console.error('解析搜索历史失败', e);
    }
  }
  
  // 加载热门城市
  await loadHotCities();
});

// 加载热门城市
const loadHotCities = async () => {
  try {
    const res = await getCityList();
    if (res && res.result && res.result[1]) {
      // 从返回的城市列表中获取一级城市
      const cityList = res.result[1];
      // 筛选出热门城市（这里取前10个一线和新一线城市）
      const popularCities = cityList
        .filter(city => city.fullname.length <= 3) // 通常热门城市名较短
        .slice(0, 10)
        .map(city => city.fullname);
      
      hotCities.value = popularCities;
    }
  } catch (error) {
    console.error('获取城市列表失败', error);
    // 保留一些热门城市作为默认值
    hotCities.value = ['北京市', '上海市', '广州市', '深圳市', '杭州市'];
  }
};

// 搜索处理
const handleSearch = async () => {
  if (!searchKeyword.value.trim()) {
    uni.showToast({
      title: '请输入搜索关键词',
      icon: 'none'
    });
    return;
  }
  
  hasSearched.value = true;
  isLoading.value = true;
  
  // 显示加载中
  uni.showLoading({
    title: '搜索中...'
  });
  
  try {
    // 调用腾讯地图关键词搜索建议API
    const res = await getSuggestion({
      keyword: searchKeyword.value,
      region: currentRegion.value
    });
    
    if (res && res.data) {
      // 转换API返回的数据格式
      searchResults.value = res.data.map(item => ({
        name: item.title,
        address: item.address || '',
        location: item.location,
        district: item.district,
        city: item.city,
        province: item.province
      }));
      
      // 保存搜索关键词到历史
      if (searchResults.value.length > 0) {
        saveSearchHistory(searchKeyword.value);
      }
    } else {
      searchResults.value = [];
    }
  } catch (error) {
    console.error('搜索位置失败:', error);
    uni.showToast({
      title: '搜索失败，请稍后再试',
      icon: 'none'
    });
    searchResults.value = [];
  } finally {
    isLoading.value = false;
    uni.hideLoading();
  }
};

// 保存搜索历史
const saveSearchHistory = (keyword) => {
  // 避免重复添加
  const index = searchHistory.value.indexOf(keyword);
  if (index !== -1) {
    searchHistory.value.splice(index, 1);
  }
  
  // 添加到最前面
  searchHistory.value.unshift(keyword);
  
  // 限制历史记录数量
  if (searchHistory.value.length > 10) {
    searchHistory.value.pop();
  }
  
  // 保存到本地存储
  uni.setStorageSync('locationSearchHistory', JSON.stringify(searchHistory.value));
};

// 删除搜索历史
const removeHistory = (index) => {
  searchHistory.value.splice(index, 1);
  uni.setStorageSync('locationSearchHistory', JSON.stringify(searchHistory.value));
};

// 选择位置
const selectLocation = (location) => {
  const pages = getCurrentPages();
  const prevPage = pages[pages.length - 2];
  
  // 如果location是完整的对象，则传递城市和区县信息
  let locationName = location.name;
  if (location.city && location.district) {
    locationName = `${location.city}${location.district}`;
  }
  
  // 触发前一个页面的事件
  if (prevPage && prevPage.$vm) {
    prevPage.$vm.$emit('locationSelected', locationName);
  }
  
  uni.navigateBack();
};

// 选择热门城市
const selectCity = (city) => {
  // 设置当前搜索区域为选中的城市
  currentRegion.value = city;
  selectLocation({ name: city });
};

// 返回
const goBack = () => {
  uni.navigateBack();
};
</script>

<style>
.location-search {
  background-color: #f8f8f8;
  min-height: 100vh;
}

.search-box {
  padding: 20rpx;
  background-color: #ffffff;
  display: flex;
  align-items: center;
}

.search-input-wrap {
  flex: 1;
  height: 70rpx;
  background-color: #f5f5f5;
  border-radius: 35rpx;
  padding: 0 20rpx;
  display: flex;
  align-items: center;
  position: relative;
}

.search-input {
  flex: 1;
  height: 100%;
  font-size: 28rpx;
}

.clear-icon {
  position: absolute;
  right: 20rpx;
  color: #999;
  font-size: 32rpx;
}

.search-btn {
  padding: 0 20rpx;
  font-size: 28rpx;
  color: #2979ff;
}

.cancel-btn {
  padding-left: 10rpx;
  font-size: 28rpx;
  color: #666;
}

.search-results {
  background-color: #ffffff;
}

.location-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx 20rpx;
  border-bottom: 1px solid #f5f5f5;
}

.item-left {
  display: flex;
  align-items: flex-start;
  flex: 1;
}

.item-icon {
  margin-right: 10rpx;
  font-size: 32rpx;
}

.item-right {
  color: #ccc;
  font-size: 36rpx;
}

.location-info {
  display: flex;
  flex-direction: column;
  margin-left: 16rpx;
  flex: 1;
}

.location-name {
  font-size: 28rpx;
  color: #333;
  margin-bottom: 6rpx;
}

.location-address {
  font-size: 24rpx;
  color: #999;
}

.empty-result {
  padding: 100rpx 0;
}

.empty-content {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.empty-icon {
  font-size: 64rpx;
  margin-bottom: 20rpx;
}

.empty-text {
  color: #999;
  font-size: 28rpx;
}

.hot-cities {
  padding: 0 20rpx 30rpx;
}

.section-title {
  font-size: 28rpx;
  color: #666;
  margin: 30rpx 0 20rpx;
}

.city-grid {
  display: flex;
  flex-wrap: wrap;
}

.city-item {
  width: 150rpx;
  height: 80rpx;
  margin-right: 20rpx;
  margin-bottom: 20rpx;
  background-color: #ffffff;
  border-radius: 8rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 28rpx;
}

.history-list {
  background-color: #ffffff;
  border-radius: 8rpx;
}

.history-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 24rpx 20rpx;
  border-bottom: 1px solid #f5f5f5;
}

.history-icon {
  margin-right: 10rpx;
  font-size: 28rpx;
}

.history-text {
  margin-left: 10rpx;
  font-size: 26rpx;
}

.close-btn {
  color: #ccc;
  font-size: 36rpx;
}

.empty-history {
  padding: 40rpx 0;
  text-align: center;
  color: #999;
  font-size: 26rpx;
}

.loading-more {
  text-align: center;
  padding: 20rpx 0;
  color: #999;
  font-size: 26rpx;
}
</style> 